package com.itcast.tanhuaserver.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itcast.tanhua.dubbo.server.api.QuanZiApi;
import com.itcast.tanhua.dubbo.server.domain.Publish;
import com.itcast.tanhuaserver.domain.User;
import com.itcast.tanhuaserver.domain.UserThreadLocal;
import com.itcast.tanhuaserver.service.QuanziMQService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @PachageName: com.itcast.tanhuaserver.service.impl
 * @ClassName:
 * @Description: TODO
 * @Author: Hushi
 * @DateTime: 2021/2/2513:49
 * @Version 1.0
 */
@Service
@Slf4j
public class QuanziMQServiceImpl implements QuanziMQService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    /**
     * 发送圈子操作相关的消息
     *
     * @param publishId
     * @param type      1-发动态，2-浏览动态， 3-点赞， 4-喜欢， 5-评论，6-取消点赞，7-取消喜欢
     * @return
     */
    private Boolean sendMsg(String publishId, Integer type){
        User user = UserThreadLocal.get();
        try {
            Publish publish = this.quanZiApi.queryPublishById(publishId);
            Map<String,Object> msg = new HashMap<>();
            msg.put("userId",user.getId());
            msg.put("date",System.currentTimeMillis());
            msg.put("publishId",publishId);
            msg.put("pid",publish.getPid());
            msg.put("type",type);
            this.rocketMQTemplate.convertAndSend("tanhua-quanzi",msg);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发送圈子操作相关的消息错误 : type=" + type + ", publishId=" + publishId,e);
            return false;
        }
        return true;
    }

    @Override
    public Boolean publishMsg(String publishId) {
        return this.sendMsg(publishId,1);
    }

    @Override
    public Boolean queryPublishMsg(String publishId) {
        return this.sendMsg(publishId,2);
    }

    @Override
    public Boolean likePublishMsg(String publishId) {
        return this.sendMsg(publishId,3);
    }

    @Override
    public Boolean disLikePublishMsg(String publishId) {
        return this.sendMsg(publishId,6);
    }

    @Override
    public Boolean lovePublishMsg(String publishId) {
        return this.sendMsg(publishId,4);
    }

    @Override
    public Boolean disLovePublishMsg(String publishId) {
        return this.sendMsg(publishId,7);
    }

    @Override
    public Boolean commentPublishMsg(String publishId) {
        return this.sendMsg(publishId,5);
    }
}
